package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.query.UpdateException;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Discription: 更新本地库存表数据状态
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/5/24 10:04
 */
@Component
@Slf4j
public class ChangeQtyStatusService {

    /**
     * 修改状态
     *
     * @param jsonArray
     */
    public void changeStatus(JSONArray jsonArray,String msgKey) {

        // synstatus = 1 时,该库存信息已经发送,更新
        String sql = "update T_IESSYNSTOCKMQ set synstatus = 1,messagekey = ? where id = ? ";
        JSONArray paramArr = new JSONArray();
        try {

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject tempObj = JSONObject.parseObject(jsonArray.get(i).toString());
                int id = tempObj.getIntValue("ID");
                QueryEngine.getInstance().executeUpdate(sql, new Object[]{msgKey,id});
            }

        } catch (Exception e) {
            // 修改库存状态失败
            log.error(e.getMessage());
        }

    }


    /**
     * 查询 并 修改数据状态为 超时数据
     */
    public void changeStatusTimeOut() {

        // 查询超出一分钟未同步的库存异动数据,并更新状态
        String querySql = "select id from T_IESSYNSTOCKMQ where synstatus = 0 and rownum < 400 and creationdate < sysdate-2/1440 ";
        JSONArray jsonArray = QueryEngine.getInstance().doQueryObjectArray(querySql);

        if (jsonArray.isEmpty() || jsonArray == null){
            return;
        }

        // 更新 synstatus = 2 ,库存异动数据已过期超时
        String updateSql = "update T_IESSYNSTOCKMQ set synstatus = 2 ,errormsg = 'time out' where id = ? ";
        QueryEngine.getInstance().executeBatchUpdate(updateSql, jsonArray);
    }




    /**
     * 查询 异常数据 并 修改数据状态为 异常数据 0 待更新 1已更新 2超时 3为负值 异常
     */
    public void changeStatusErro() {

        // 查询异常库存异动数据,并更新状态
        String querySql = "select id from T_IESSYNSTOCKMQ where synstatus = 0 and syncnum < 0 and rownum < 400 ";
        JSONArray jsonArray = QueryEngine.getInstance().doQueryObjectArray(querySql);

        if (jsonArray.isEmpty() || jsonArray == null) {
            return;
        }

        // 更新 synstatus = 4 ,库存异动数据为负
        String updateSql = "update T_IESSYNSTOCKMQ set synstatus = 3 ,errormsg = 'sycnnum is minus' where id = ? ";
        QueryEngine.getInstance().executeBatchUpdate(updateSql, jsonArray);


    }






    }
